package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.SoulConstants;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.SoundApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Sound;
import com.tanhua.model.vo.SoundVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Set;

@Service
public class PeachBlossomService {

    @Autowired
    private FastFileStorageClient client; //从调度服务器获取，一个目标存储服务器，上传
    @Autowired
    private FdfsWebServer webServer;// 获取存储服务器的请求URL
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private SoundApi soundApi;

    /**
     * 发送语音
     * @param soundFile
     */
    public void sendSound(MultipartFile soundFile) {

        Long userId = UserHolder.getUserId();
        String key = SoulConstants.SEND_SOUND_TIMES + userId;
        String timeStr = redisTemplate.opsForValue().get(key);
        int time = 0;
        if(StringUtils.isNotEmpty(timeStr)) {
            time = Integer.parseInt(timeStr);
            if (time == 3) {
                throw new TanHuaException("今日发送语音次数已用完");
            }
        }

        String filename = soundFile.getOriginalFilename();
        String extension = filename.substring(filename.lastIndexOf(".")+1);
        try {
            StorePath path = client.uploadFile(soundFile.getInputStream(), soundFile.getSize(), extension, null);
            String soundUrl = webServer.getWebServerUrl() + path.getFullPath();

            UserInfo userInfo = userInfoApi.getById(userId);
            Sound sound = new Sound();
            sound.setUserId(userInfo.getId());
            sound.setGender(userInfo.getGender());
            sound.setSoundUrl(soundUrl);
            soundApi.save(sound);
            //使用次数写入redis
            redisTemplate.opsForValue().set(key, time + 1 + "");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 接收语音
     * @return
     */
    public SoundVo receiveSound() {
        Long userId = UserHolder.getUserId();
        String key = SoulConstants.GET_SOUND_TIMES + userId;
        String timeStr = redisTemplate.opsForValue().get(key);
        int time = 3;
        UserInfo userInfo = userInfoApi.getById(userId);
        if(StringUtils.isNotEmpty(timeStr)) {
            time = Integer.parseInt(timeStr);
        }
        if(time == 0) {
            return SoundVo.init(userInfo, new Sound(), 0);
        }

        String alreadyGetSoundKey = SoulConstants.ALREADY_GET_SOUND + userId;
        //获取已经获取的语音ids
        Set<String> redisIds = redisTemplate.opsForSet().members(alreadyGetSoundKey);

        Sound sound = soundApi.getOne(userId, userInfo.getGender(), redisIds);
        if(null == sound)
            throw new TanHuaException("暂无推荐,请稍后再试");
        redisTemplate.opsForSet().add(alreadyGetSoundKey, sound.getId().toHexString());

        UserInfo soundUserInfo = userInfoApi.getById(sound.getUserId());
        SoundVo result = SoundVo.init(soundUserInfo, sound, time);
        time--;
        redisTemplate.opsForValue().set(key, time+"");
        return result;
    }
}
